package No0002_add_two_numbers

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	head := new(ListNode)
	p1 := l1
	p2 := l2
	pr := head
	carry := 0
	for true {
		if p1 == nil && p2 == nil && carry == 0 {
			break
		}
		tmpVal := carry
		carry = 0
		if p1 != nil {
			tmpVal += p1.Val
		}
		if p2 != nil {
			tmpVal += p2.Val
		}
		if tmpVal > 9 {
			carry = 1
			pr.Val = tmpVal % 10
		} else {
			pr.Val = tmpVal
		}
		if (p1 != nil && p1.Next != nil) || (p2 != nil && p2.Next != nil) || carry != 0 {
			pr.Next = new(ListNode)
		}
		pr = pr.Next
		if p1 != nil {
			p1 = p1.Next
		}
		if p2 != nil {
			p2 = p2.Next
		}
	}
	if carry != 0 {
		pr = new(ListNode)
		pr.Val = carry
	}
	return head
}

var Solution func(l1 *ListNode, l2 *ListNode) *ListNode = addTwoNumbers
